<?php

namespace frontend\modules\demo\controllers;

use common\models\Article;
use yii\helpers\ArrayHelper;
use yii\web\Controller;

/**
 * Default controller for the `demo` module
 */
class HeplerController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionArray(){

        //对象转换为数组


        $article = Article::find()->joinWith('category')->limit(3)->all();

        $data =  ArrayHelper::toArray($article,['common\models\Article'=>[
            'id',
            'slug',
            'google'=>function($article){
            return $article->created_at;
            }
        ]]);


        print_r($data);die;




        //HTML 编码和解码值


//        $encoded = ArrayHelper::htmlEncode($data);
//        $decoded = ArrayHelper::htmlDecode($data);




        //建立哈希表

        $array = [
            ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
            ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
            ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
        ];

        $result = ArrayHelper::map($array, 'id', 'name');
// 结果是：
// [
//     '123' => 'aaa',
//     '124' => 'bbb',
//     '345' => 'ccc',
// ]

        $result = ArrayHelper::map($array, 'id', 'name', 'class');
// 结果是：
// [
//     'x' => [
//         '123' => 'aaa',
//         '124' => 'bbb',
//     ],
//     'y' => [
//         '345' => 'ccc',
//     ],
// ]



        //获取某列
        $array = [
            ['id' => '123', 'data' => 'abc'],
            ['id' => '345', 'data' => 'def'],
        ];
        $ids = ArrayHelper::getColumn($array, 'id');

        //如果需要额外的转换或者取值的方法比较复杂， 第二参数可以指定一个匿名函数：

        $result = ArrayHelper::getColumn($array, function ($element) {
            return $element['id'];
        });

        print_r($ids);die;


       // 重建数组索引

        $array = [
            ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
            ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
            ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
        ];
        $result = ArrayHelper::index($array, 'id');



        //设置数组和获取数组

        $array = [
            'key' => [
                'in' => ['k' => 'value']
            ]
        ];

        ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);
// 在 `$array` 中写入值的路径可以被指定为一个数组
        ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);


        print_r($array);


        $value = ArrayHelper::getValue($array,'key.in');
        print_r($value);

    }
}
